package com.atguigu.service.impl;

import com.atguigu.dao.BookDao;
import com.atguigu.dao.OrderDao;
import com.atguigu.dao.OrderItemDao;
import com.atguigu.dao.impl.BookDaoImpl;
import com.atguigu.dao.impl.OrderDaoImpl;
import com.atguigu.dao.impl.OrderItemDaoImpl;
import com.atguigu.pojo.*;
import com.atguigu.service.OrderService;

import javax.swing.text.TableView;
import java.util.Date;
import java.util.List;

public class OrderServiceImpl implements OrderService {
    OrderDao orderDao=new OrderDaoImpl();
    OrderItemDao orderItemDao=new OrderItemDaoImpl();
    BookDao bookDao=new BookDaoImpl();
    @Override
    public String createOrder(Cart cart, Integer userId) {
        System.out.println("OrderServiceImpl程序在["+Thread.currentThread().getName()+"]线程中");
        String orderId=System.currentTimeMillis()+""+userId+(int)(Math.random()*100);//随机数 1611805551563:1:38

        Order order=new Order(orderId,new Date(),cart.getTotalPrice(),0,userId);
        orderDao.saveOrder(order);
        try {//这里可以不写,因为这是用于测试中间环节有异常,是否可以立即返回调用者身上,而不继续执行中间环节的实验
            //int i=12/0;
        }catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException(e);//遇到异常,要往上层抛,才行,不能自己知道,自己捂起来
        }
        //System.out.println("你看看他还执行吗?");
        for (CartItem value : cart.getItems().values()) {
            OrderItem orderItem=new OrderItem(null,value.getName(),value.getCount(),value.getPrice(),value.getTotalPrice(),order.getOrderId());
            orderItemDao.saveOrderItem(orderItem);
            Book book=bookDao.queryBookById(value.getId());
            book.setSales(book.getSales()+value.getCount());
            book.setStock(book.getStock()-value.getCount());
            bookDao.updateBook(book);
        }
        cart.clear();//这里忘记了.尴尬
        return orderId;
    }

    @Override
    public List<Order> showAllOrders() {
        List<Order> orders=orderDao.queryOrders();
        return orders;
    }

    @Override
    public Integer sendOrder(String orderId) {
        Integer result=orderDao.changeOrderStatus(orderId,1);
        return result;
    }

    @Override
    public List<OrderItem> showOrderDetail(String orderId) {
        List<OrderItem> orderItems=orderItemDao.queryOrderItemsByOrderId(orderId);
        return orderItems;
    }

    @Override
    public List<Order> showMyOrders(Integer userId) {
        List<Order> orders=orderDao.queryOrderByUserId(userId);
        return orders;
    }

    @Override
    public Integer receiveOrder(String orderId) {
        Integer result=orderDao.changeOrderStatus(orderId,2);
        return result;
    }
}
